package com.lonwin.inspectionmanagement.app.utils;

import android.animation.ObjectAnimator;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.View;

import com.jess.arms.utils.DataHelper;
import com.lonwin.inspectionmanagement.app.AppConstants;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.ConfigBean;

import java.io.Closeable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

import static com.jess.arms.utils.DataHelper.getDeviceData;

/**
 * Author:zhangjing
 * Time:2018/6/29  下午2:37
 * Name: this is AppUtil
 * Email:zhangjingworkmol@163.com
 */

public class AppUtil {
//
//    public static String preUrl="http://oss.lonhcloud.cn/lhcenter/api/v1/oss/";
    public AppUtil() {
        throw new AssertionError("你不能初始化工具类");
    }

    /**
     * 统一驱动service 解决兼容性问题
     * @param context
     * @param intent
     * @return
     */
    public static void startService(Context context,Intent intent)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
    }

    public static boolean saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "xcgl";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".png";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
            fos.close();

            //把文件插入到系统图库
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 通过uri获取bitmap
     * @param uri
     * @return
     */
    public static void getBitmapFromUri(Context context,Uri uri)
    {
        try
        {
            // 读取uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
            saveImageToGallery(context,bitmap);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    /**
     * 根据int状态获取巡查记录表的显示状态
     * @param stepstatus
     * @return
     */
    public static String  getStrStatus_new(int stepstatus)
    {
        String tem="";
        switch (stepstatus)
        {
            case 0:
                tem="待提交";
                break;
            case 1:
                tem="待签批";
                break;
            case 2:
                tem="已签批";
                break;
            case 3:
                tem="已存档";
                break;
            default:
                tem="已存档";
                break;
        }
        return tem;
    }
    /**
     * 根据int状态获取巡查记录表的显示状态
     * @param stepstatus
     * @return
     */
   public static String  getStrStatus(int stepstatus)
   {
       String tem="";
     switch (stepstatus)
     {
         case 0:
             tem="（待提交）";
             break;
         case 1:
             tem="（待签批）";
             break;
         case 2:
             tem="（已签批）";
             break;
         case 3:
             tem="（已存档）";
             break;
             default:
                 tem="（已存档）";
                 break;
     }
     return tem;
   }
    /**
     * 获取默认的河湖id
     * @return
     */
    public static  String getgroupids(ConfigBean configBean){
        String groupids="";

            for (int i=0;i<configBean.getRiverDatas().size();i++)
            {
                if (configBean.getRiverDatas().get(i).getChildren()!=null&&!configBean.getRiverDatas().get(i).getChildren().isEmpty())
                {
                    for (int m=0;m<configBean.getRiverDatas().get(i).getChildren().size();m++)
                    {
                        groupids+=String.valueOf(configBean.getRiverDatas().get(i).getChildren().get(m).getId())+",";
                    }
                }
            }
            return groupids.length()>1?groupids.substring(0,groupids.length()-1):"";




//    public static  String getgroupids(ConfigBean configBean){
//        String groupids="";
//
//        if (AppConstants.ROLE_HZB.equals(configBean.getCurrentRole().getRoleCode())||AppConstants.ROLE_HZB.equals("ROLE_ZHZ")
//                ||AppConstants.ROLE_HZB.equals("ROLE_FZHZ")||AppConstants.ROLE_HZB.equals("ROLE_ZDC")||AppConstants.ROLE_HZB.equals("ROLE_FZDC"))
//        {
//            if (!configBean.isHasTree()){
//                //没有树的情况
//                for (int i=0;i<configBean.getRiverDatas().size();i++)
//                {
//                    if (i==0)
//                    {
//                        groupids+=String.valueOf(configBean.getSelfRiver().get(i).getId());
//                    }else {
//                        groupids=groupids+","+String.valueOf(configBean.getSelfRiver().get(i).getId());
//                    }
//                }
//                return groupids;
//            }
//            for (int i=0;i<configBean.getRiverDatas().size();i++)
//            {
//                if (configBean.getRiverDatas().get(i).getChildren()!=null&&!configBean.getRiverDatas().get(i).getChildren().isEmpty())
//                {
//                    for (int m=0;m<configBean.getRiverDatas().get(i).getChildren().size();m++)
//                    {
//                        groupids+=String.valueOf(configBean.getRiverDatas().get(i).getChildren().get(m).getId())+",";
//                    }
//                }
//            }
//            return groupids.length()>1?groupids.substring(0,groupids.length()-1):"";
//        }
//        if (configBean.getSelfRiver()==null||configBean.getSelfRiver().isEmpty())
//        {
//
//            return groupids;
//        }
//
//        for (int i=0;i<configBean.getSelfRiver().size();i++)
//        {
//            if (i==0)
//            {
//                groupids+=String.valueOf(configBean.getSelfRiver().get(i).getId());
//            }else {
//                groupids=groupids+","+String.valueOf(configBean.getSelfRiver().get(i).getId());
//            }
//        }
//        return groupids;
    }
    /**
     * 得到默认的配置信息
     *
     * @param mcontext
     * @param fileName
     * @return
     */
    public static String getConfigFile(Context mcontext, String fileName) {
        try {
            InputStream is = mcontext.getAssets().open("file/" + fileName);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            String text = new String(buffer, "utf-8");
            return text;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 格式化保留两位小数
     * @param num
     * @return
     */
    public static String formTowPoint(double num)
    {
        DecimalFormat df1 = new DecimalFormat("#.00");    //##.00%   百分比格式，后面不足2位的用0补齐
        return df1.format(num);
    }

  public static void setAnimator(View view){
      ObjectAnimator animator = ObjectAnimator.ofFloat(view, "scaleY", 0f, 1f);
      animator.setDuration(500);
      animator.start();
  }


    public static File uriToFile(Uri uri, Context context) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = context.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA }, buff.toString(), null, null);
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    System.out.println("temp uri is :" + u);
                }
            }
            if (path != null) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();

            return new File(path);
        } else {
            //Log.i(TAG, "Uri Scheme:" + uri.getScheme());
        }
        return null;
    }

    public static String convert2HttpUrl(String url){
        if (url.startsWith("http")){
            return url;
        }else {
            return "http://"+url;
        }
    }

    public static String getFromMediaUri(Context context, ContentResolver resolver, Uri uri) {
        if (uri == null) return null;

        FileInputStream input = null;
        FileOutputStream output = null;
        try {
            ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
            if (pfd == null) {
                return null;
            }
            FileDescriptor fd = pfd.getFileDescriptor();
            input = new FileInputStream(fd);

            String tempFilename = getTempFilename(context);
            output = new FileOutputStream(tempFilename);

            int read;
            byte[] bytes = new byte[4096];
            while ((read = input.read(bytes)) != -1) {
                output.write(bytes, 0, read);
            }

            return new File(tempFilename).getAbsolutePath();
        } catch (Exception ignored) {

            ignored.getStackTrace();
        } finally {
            closeSilently(input);
            closeSilently(output);
        }
        return null;
    }

    private static String getTempFilename(Context context) throws IOException {
        File outputDir = context.getCacheDir();
        File outputFile = File.createTempFile("image", "tmp", outputDir);
        return outputFile.getAbsolutePath();
    }

    public static void closeSilently(@Nullable Closeable c) {
        if (c == null) return;
        try {
            c.close();
        } catch (Throwable t) {
            // Do nothing
        }
    }

//    public static String prePicUrl(){
//       String url= "http://oss.lonhcloud.cn/lhcenter/api/v1/oss/";
//       return url;
//    }

}
